/**
*    Copyright (C) 2008  Chase Kernan 
*    chase.kernan@gmail.com
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
*/

package com.chasekernan.hxnova.server.functions;

import com.chasekernan.hxnova.core.dataholders.Global;
import com.chasekernan.hxnova.core.fleets.Fleet;
import com.chasekernan.hxnova.core.stars.Star;

/**
    Repairs fleets.
**/
class Repairing {
    
    /**
        The rate at which fleets repair in space.
    **/
    public static var IN_SPACE_REPAIR_RATE = 0.01;
    
    /**
        The rate at which fleets repair in orbit.
    **/
    public static var IN_ORBIT_REPAIR_RATE = 0.1;
    
    /**
        The rate at which fleets repair in orbit of a friendly starbase.
    **/
    public static var FRIENDLY_STARBASE_REPAIR_RATE = 0.4;
    
    public static function run() {
        for (fleet in Global.fleets) {
			for (stack in fleet.ships) {
				
				var maxArmor = stack.type.getArmor();
				
				if (stack.armor != stack.type.getArmor()) {
					var star = Global.stars.getStarAtLocation(fleet.location);
					
					var repair = stack.armor;
					
					if (star == null) repair *= 1 + IN_SPACE_REPAIR_RATE;
					else {
						var friendlyStarbase = switch (star.starbase) {
							
							case Design(d):
								if (star.owner.id == fleet.owner.id || 
										star.owner.relations.isFriendOf(fleet.owner))
									true
								else
									false;
									
							case None:
								false;
						}
						
						repair *= 1 + if (friendlyStarbase) 
											FRIENDLY_STARBASE_REPAIR_RATE
									  else					
									  		IN_ORBIT_REPAIR_RATE;
					}
					
					stack.armor = Std.int(Math.min(maxArmor, repair));
				}
			}
        }
    }
}